package com.wanyl.test;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;

public class staticHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange)  {
        String[] ifile = exchange.getRequestURI().toString().split("/");
        String filename = ifile[ifile.length - 1];
        System.out.println("sned File:"+filename);
        try{
            InputStream in = getResOut(filename);

            int len = 4096;
            byte[] data = new byte[len];

            for(;;) {
                if(in==null)break;
//                MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
                String[] name = filename.split("\\.");

//                System.out.println("文件检测");
//                System.out.println(name.length);
                if (name.length == 0) break;
                System.out.println("文件检测完成");

//                String types = new MimetypesFileTypeMap().getContentType("."+name[name.length - 1]);
//                System.out.println("检测转换类型:"+types);
                exchange.sendResponseHeaders(200,0);
                exchange.getResponseHeaders().add("Content-Type", "javascript; charset=utf-8");
                OutputStream dd = exchange.getResponseBody();
                int readline;
                System.out.println("正在写入缓冲");

                while (( readline = in.read(data)) > 0) {
//                    System.out.println("准备写入"+readline);

                    exchange.getResponseBody().write(data,0,readline);
//                    dd.flush();
                    if (readline < len) {
//                        System.out.println("跳出循环");
                        break;}
//                    System.out.println("发送中");
                }
                break;
            }
//            dd.close();
        }catch (Exception e){
            e.printStackTrace();
            try {
                exchange.sendResponseHeaders(404,0);
            } catch (IOException ioException) {
//                ioException.printStackTrace();
            }
        }
//        System.out.println("发送成功");
        exchange.close();
    }

    public InputStream getResOut(String filename){
        File file = new File("src/www/"+filename);
        if(file.exists()){
            InputStream in =null;
            try{in= new FileInputStream(file);}catch (Exception e){}
            if(in!=null)return in;
        }
        InputStream in = this.getClass().getResourceAsStream("/www/"+filename);

        if(in==null) {System.out.println("[data] 获取资源失败");}else {
            System.out.println("[data] 资源获取成功");
        }

        return in;
    }
}
